#!/bin/bash
set -e
echo "<--------建木npm发布节点-------->"
#路径必填
if [[ ! -z "${JIANMU_DIR}" ]]; then
    cd ${JIANMU_DIR}
else
    echo "【建木警告】待发布包路径未填"
    exit 1
fi

if [[ ! -e "package.json" ]]; then
    #检测package.json是否存在
    echo "【建木警告】包中不存在package.json文件"
    exit 1
fi

if [[ ! -e "README.md" ]]; then
    echo "【建木提示】包中不存在README文件，建议补全"
fi

#仓库和用户token必填
if [[ ! -z "${JIANMU_USER_TOKEN}" ]] && [[ ! -z "${JIANMU_REGISTRY}" ]]; then
    #去掉仓库url前面的https或者http，将token和对应仓库写到.nmprc文件中
    if [[ ${JIANMU_REGISTRY:4:1} == "s" ]]; then
        echo "${JIANMU_REGISTRY:6}:_authToken=${JIANMU_USER_TOKEN}" >/root/.npmrc
    else
        echo "${JIANMU_REGISTRY:5}:_authToken=${JIANMU_USER_TOKEN}"
        echo "${JIANMU_REGISTRY:5}:_authToken=${JIANMU_USER_TOKEN}" >/root/.npmrc
    fi
    npm config set registry "${JIANMU_REGISTRY}"
else
    echo "用户token未输入"
fi

if [[ ! -z ${JIANMU_VERSION} ]]; then
    npm version ${JIANMU_VERSION}
fi

# 如果有tag参数传入
if [[ ! -z ${JIANMU_TAG} ]]; then
    npm publish --tag ${JIANMU_TAG}
else
    npm publish
fi

package_name=$(cat package.json | jq .name)
package_version=$(cat package.json | jq .version)

echo -e "{\"package_name\" : ${package_name},\"package_version\" : ${package_version},\"publish_registry\" : \"${JIANMU_REGISTRY}\"}" >/usr/resultFile

echo "<-----------发布成功----------->"
